/*
* 计时器
* */
import {useEffect, useState} from "react";

const useTime = () => {
    const [time, setTime] = useState<number>(0)

    useEffect(() => {
        let intervalId: undefined | number | NodeJS.Timeout = undefined;
        if (time > 0) {
            intervalId = setInterval(() => {
                setTime(time => time - 1);
            }, 1000)
        } else if (time === 0) {
            if (intervalId) {
                clearInterval(intervalId)
                intervalId = undefined
            }

        }
        return () => {
            intervalId && clearInterval(intervalId as number)
            intervalId = undefined
        }
    }, [time]);

    const changeTime = (t: number, callback: Function | null = null) => {
        if (callback) callback()
        setTime(t)
    }
    return { time, changeTime }
}

export default useTime